/**
* @CopyRight tstudy.com.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.weike;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.ResponseHandlerInterface;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.BaseOnScrollListener;
import com.tstudy.laoshibang.base.BaseOnScrollListener.LoadMoreCallBack;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.CONSTANT.LoadType;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.base.IndexActivity;
import com.tstudy.laoshibang.event.ChangeGroupEvent;
import com.tstudy.laoshibang.event.WeikeLoveEvent;
import com.tstudy.laoshibang.event.WeikePlayEvent;
import com.tstudy.laoshibang.mode.Adverts;
import com.tstudy.laoshibang.mode.Weike;
import com.tstudy.laoshibang.mode.request.Conds;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.mode.response.WeikeListResponse;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;
import com.tstudy.laoshibang.weike.WeikeListAdapter.AdapterCallBack;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.greenrobot.event.EventBus;
@SuppressLint("InflateParams")
@EFragment(R.layout.weike_list)
public class WeikeListFragment extends BaseFragment{
	final static String TAG = "weike_list";
	public WeikeListFragment() {
		super();
	}
	
	@ViewById(R.id.weike_list_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.weike_list_progress)
	RelativeLayout mProgressLayout;
	
	@ViewById(R.id.weike_list_title)
	TextView mTitleTxt;
	
	@ViewById(R.id.weike_list_list)
	PullToRefreshListView mPullToRefreshListView;
	
	BaseOnScrollListener mBaseOnScrollListener;
	LoadType mLoadType;
	
	boolean mIsFirstLoad = true;
	Handler mHandler;
	LayoutInflater mInflater;
	WeikeListAdapter mWeikeListAdapter;
	RelativeLayout mHeaderLayout;
	TextView mCategoryTxt;
	TextView mPriceTxt;
	TextView mLocationTxt;
	RelativeLayout mCategoryLayout;
	RelativeLayout mPriceLayout;
	RelativeLayout mLocationLayout;
	LinearLayout mViewPagerSelectLayout;
	ViewPager mViewPager;
	ImageView mEmptyView;
	int mHeaderHeight = (int)(BaseApplication.mScreenWidth*CONSTANT.weike_header_scale);
	ListItemPageAdapter mPageAdapter;
	
	public List <Adverts>mAdverts = new ArrayList<Adverts>();
	
	public static final int BANNER_DURATION = 3000;
	int mCurrentPosition = 0;
	List<View> mViewList = new ArrayList<View>();
	List<Weike> mWeikes = new ArrayList<Weike>();
	@StringRes(R.string.select_all)
	String mSelectAllStr;
	int mSelectAllKey = -1;

	public static void add(int containerViewId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		Fragment fragment = ((BaseActivity)BaseApplication.mCurrentActivity).getFragmentByTag(TAG);
		if(fragment == null){
			fragment = Fragment.instantiate(BaseApplication.mContext,WeikeListFragment_.class.getName(),args);
		}
		((BaseActivity)BaseApplication.mCurrentActivity).addInTab(containerViewId,fragment,TAG);	
	
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		EventBus.getDefault().register(this);
		super.onCreate(savedInstanceState);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}

	public void onEventMainThread(Object object) {
		if(object instanceof WeikeLoveEvent){
			WeikeLoveEvent event = (WeikeLoveEvent) object;
			mWeikes.get(event.position).isPraise = event.isPrised;
			if (event.isPrised == CONSTANT.IS_PRISED) {
				mWeikes.get(event.position).praiseNum++;
			}else{
				mWeikes.get(event.position).praiseNum--;
			}
			mWeikeListAdapter.setData(mWeikes);
		}else if(object instanceof WeikePlayEvent){
			WeikePlayEvent event = (WeikePlayEvent) object;
			mWeikes.get(event.position).playNum++;
			mWeikeListAdapter.setData(mWeikes);
		}else if(object instanceof ChangeGroupEvent){
			mLoadType = LoadType.load_first;
			if (BaseApplication.mCurrentGroup != null) {
				mTitleTxt.setText(BaseApplication.mCurrentGroup.name +CONSTANT.GROUP_SEPEREATE+ BaseApplication.getResString(R.string.weike_list_title));
			}
			getWeikeList();
		}
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			if (BaseApplication.mCurrentGroup != null) {
				mTitleTxt.setText(BaseApplication.mCurrentGroup.name +CONSTANT.GROUP_SEPEREATE+ BaseApplication.getResString(R.string.weike_list_title));
			}
			initHeaderView();
			mPageAdapter = new ListItemPageAdapter();
			mViewPager.setAdapter(mPageAdapter);
			mViewPager.setOnPageChangeListener(mPageAdapter);
			mWeikeListAdapter = new WeikeListAdapter();
			mPullToRefreshListView.setAdapter(mWeikeListAdapter);
			mWeikeListAdapter.setAdatperCallBack(new AdapterCallBack() {
				@Override
				public void onAvatorClick(int weikeId,int position) {
					WeikeDetailPlayerFragment.add(mFragmentId, weikeId,position);
				}
				@Override
				public void onLoveClick(Weike weike, int position,TextView view) {
					loveAction(weike, CONSTANT.ASSO_TYPE_WEIKE, weike.isPraise==0?CONSTANT.UNLOVE_ACTION:CONSTANT.LOVE_ACTION, view);
				}
			});
			mPullToRefreshListView.getRefreshableView().addHeaderView(mHeaderLayout);
			mLoadType = LoadType.load_first;
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					getWeikeList();
				}
			}, CONSTANT.LOAD_DATA_DELAY_TIME);
			mBaseOnScrollListener = new BaseOnScrollListener(new LoadMoreCallBack() {
				@Override
				public void loadMore() {
					mPullToRefreshListView.startLoadMore();
					mLoadType = LoadType.load_more;
					getWeikeList();
				}
			});
			mPullToRefreshListView.setOnScrollListener(mBaseOnScrollListener);
			mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
				@Override
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					mLoadType = LoadType.load_refresh;
					getWeikeList();
				}
			});
		}
	}
	@Click(R.id.weike_list_title_opengroup)
	public void showGroupPop() {
		((IndexActivity)getActivity()).showGroupPop();
	}
	public void fillAdverts(){
		mViewList.clear();
		if (mAdverts != null) {
			int size = mAdverts.size();
			if (size > 0) {
				mViewPager.setVisibility(View.VISIBLE);
			}
			for (int i = 0; i < size; i++) {
				final Adverts each = mAdverts.get(i);
				RelativeLayout layout = (RelativeLayout) mInflater.inflate(R.layout.list_header_pager, null);
				ImageView img = (ImageView) layout.findViewById(R.id.list_header_pager_img);
				ImageView videoIcon = (ImageView) layout.findViewById(R.id.list_header_pager_video_icon);
				TextView title = (TextView) layout.findViewById(R.id.list_header_pager_title);
				videoIcon.setVisibility(View.VISIBLE);
				ImageView leftIcon = (ImageView) layout.findViewById(R.id.list_header_pager_left_icon);
				ImageView rightIcon = (ImageView) layout.findViewById(R.id.list_header_pager_right_icon);
				if (i == 0) {
					if (size == 1) {
						leftIcon.setVisibility(View.GONE);
						rightIcon.setVisibility(View.GONE);
					}else{
						leftIcon.setVisibility(View.GONE);
						rightIcon.setVisibility(View.VISIBLE);
					}
				}else if(i == size -1){
					leftIcon.setVisibility(View.VISIBLE);
					rightIcon.setVisibility(View.GONE);
				}else{
					leftIcon.setVisibility(View.VISIBLE);
					rightIcon.setVisibility(View.VISIBLE);
				}
				HttpManager.getInstance().loadCommonImage(img, each.imgIdxName + CommonUtil.buildCropUrl(BaseApplication.mScreenWidth, mHeaderHeight));
				title.setText(each.title);
				mViewList.add(layout);
				img.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (each.isRedirect == 1) {
						}else{
//							WeikeDetailFragment.add(mFragmentId,each.assoId);
							WeikeDetailPlayerFragment.add(mFragmentId,each.assoId,-1);
						}
					}
				});
//				fillSelectLayout(mViewPagerSelectLayout, i);
			}
			mPageAdapter.setData(mViewList);
			addCallBacks();
		}
		
	}
	
	@SuppressLint("InflateParams")
	public void initHeaderView(){
		mHeaderLayout = (RelativeLayout) mInflater.inflate(R.layout.weike_list_header, null);
		mViewPager = (ViewPager) mHeaderLayout.findViewById(R.id.weike_list_header_viewpage);
		mEmptyView = (ImageView) mHeaderLayout.findViewById(R.id.weike_list_header_empty_view);
		mEmptyView.getLayoutParams().height = mHeaderHeight;
		mViewPager.getLayoutParams().height = mHeaderHeight;
	}
	
	int mIndexMargin = CommonUtil.dip2px(6);
	public void fillSelectLayout(LinearLayout layout,int position){
		ImageView image = new ImageView(BaseApplication.mContext);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
		lp.setMargins(mIndexMargin, 0, mIndexMargin, 0);
//		image.setImageResource(R.drawable.weike_list_pager_selector);
		if (position == 0) {
			image.setSelected(true);
		}
		layout.addView(image, lp);
	}

	class ListItemPageAdapter extends PagerAdapter implements OnPageChangeListener{
		List<View> mViewList = new ArrayList<View>();
		public void setData(List<View> viewList){
			mViewList = viewList;
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return mViewList.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
		
		 @Override  
		    public void destroyItem(ViewGroup container, int position,Object object) { 
			 if(mViewList.size() > 1) {
				 container.removeView(mViewList.get(position));  
			 }else {
				 container.removeView((View) object);
			 }

		    }  

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(mViewList.get(position));
			return mViewList.get(position);
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onPageSelected(int position) {
			changeSelectBg(position);
			
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			// TODO Auto-generated method stub
		}
		
	}

	public void changeSelectBg(int position) {
		if (mViewPagerSelectLayout != null) {
//			mViewPagerSelectLayout.getChildAt(position).setSelected(true);
//			mCurrentPosition = position;
//			int childCount = mViewPagerSelectLayout.getChildCount();
//			for (int i = 0; i < childCount; i++) {
//				mViewPagerSelectLayout.getChildAt(i).setSelected(i == position);
//			}
			addCallBacks();
		}
	}
	
	public void removeCallbacks(){
		mHandler.removeCallbacks(changeHeaderTask);
	}
	
	public void addCallBacks(){
		removeCallbacks();
		mHandler.postDelayed(changeHeaderTask, BANNER_DURATION);
	}
	Runnable changeHeaderTask = new Runnable() {
		@Override
		public void run() {
			int size = mViewList.size();
			mCurrentPosition++;
			if (mCurrentPosition == size) {
				mCurrentPosition = 0;
			}
			mViewPager.setCurrentItem(mCurrentPosition);
		}
	};
	
	/**
	 * 微课点赞
	 * @param activeId
	 * @param type
	 * @param isPraise
	 */
	private void loveAction(final Weike weike,int type,final int isPraise,final TextView loveCountTxt){
		BaseListJsonHandler<BaseResponse> response = new BaseListJsonHandler<BaseResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
//					int count = weike.isPraise==1?weike.praiseNum-1:weike.praiseNum +1;
//					loveCountTxt.setText(count+"");
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					BaseResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().loveAction(BaseApplication.mUserNo, type, weike.coseId, isPraise,null, response);
	}
	
	private void getWeikeList(){
		if (mIsLoading) {
			return ;
		}
		int isAdt = 1;
		if (mLoadType == LoadType.load_more) {
			start += pageSize;
			isAdt = 0;
		}else{
			start = 0;
			limit = pageSize;
		}
		mIsLoading = true;
		ResponseHandlerInterface response = new BaseListJsonHandler<WeikeListResponse>() {
			public void onStart() {
				if (mLoadType == LoadType.load_first) {
					showProgressBar(mProgressLayout);
				}
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, WeikeListResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (response.getData() != null && response.getData().getAdverts() != null && response.getData().getAdverts().size() > 0) {
						if(mAdverts != null || mAdverts.size() != 0) {
							mAdverts.clear();
						}
						mAdverts = response.getData().getAdverts();
						fillAdverts();
					}else {
						mViewPager.setVisibility(View.INVISIBLE);
					}
					if (response.getData() != null) {
						if (mLoadType == LoadType.load_more) {
							if (mWeikes.size() == response.getData().getCount()) {
								mBaseOnScrollListener.mIsEnd = true;
							}
						}else{
							mWeikes.clear();
						}
						List<Weike> list = response.getData().getList();
						if (list != null) {
							mWeikes.addAll(list);
						}
						mWeikeListAdapter.setData(mWeikes);
					}
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					WeikeListResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected WeikeListResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,WeikeListResponse.class);
			}
		};
		List<Conds> conds = new ArrayList<Conds>();
//		if (BaseApplication.mCurrentGroup != null) {
//			conds.add(new Conds("groupId",BaseApplication.mCurrentGroup.groupId));
//		}
		HttpManager.getInstance().getWeikeList(BaseApplication.mUserNo,start,limit,null,conds,isAdt, response);
	}

	public void afterLoading(){
		mIsLoading = false;
		hideProgressBar(mProgressLayout);
		if(mLoadType == LoadType.load_more){
			if (mBaseOnScrollListener.mIsEnd) {
				mPullToRefreshListView.endLoadMore(BaseApplication.getResString(R.string.weike_no_more_data));
			}else{
				mPullToRefreshListView.stopLoadMore();
			}
		}
		if(mPullToRefreshListView != null){
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if(mPullToRefreshListView != null){
						mPullToRefreshListView.onRefreshComplete();
						LogUtil.d("--onRefreshComplete afterloading");
					}
				}
			}, 1000);
		}
	
	}
	@Click(R.id.weike_list_search)
	public void showSearchDialog(){
		WeikeSearchFragment.add(mFragmentId);
	}
	@Override
	public void clear() {
		// TODO Auto-generated method stub
	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}
	
	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
		}
	}

}
